package com.zy.openchat.util;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Vibrator;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.google.gson.Gson;
import com.zy.openchat.App;
import com.ja.openchat.ui.MainActivity;
import com.ja.openchat.R;
import com.zy.openchat.core.model.message.MessageInfo;

public class LocalNotificationHelper {
    public static final int LOCAL_NOTIFICATION_TYPE_MESSAGE = 1;

    @TargetApi(26)
    private static NotificationChannel getMessageChannel(String channelId) {
        String channelName = App.getInstanse().getResources().getString(R.string.app_name);
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
        //是否绕过请勿打扰模式
        channel.canBypassDnd();
        //闪光灯
        channel.enableLights(true);
        //锁屏显示通知
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        //闪关灯的灯光颜色
        channel.setLightColor(Color.RED);
        //桌面launcher的消息角标
        channel.canShowBadge();
        //是否允许震动
        channel.enableVibration(true);
        //获取系统通知响铃声音的配置
        channel.getAudioAttributes();
        //获取通知取到组
        channel.getGroup();
        //设置可绕过  请勿打扰模式
        channel.setBypassDnd(true);
        //设置震动模式
        channel.setVibrationPattern(new long[]{100, 100, 200});
        //是否会有灯光
        channel.shouldShowLights();
        return channel;
    }

    public static void showMessageNotification(Context context, MessageInfo msg) {
        //手机是否静音或者只震动
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        final int ringerMode = audioManager.getRingerMode();
        switch (ringerMode) {
            case AudioManager.RINGER_MODE_NORMAL:
                //normal
                //不做处理
                break;
            case AudioManager.RINGER_MODE_VIBRATE:
                //vibrate
                playRingtone(context);
                break;
            case AudioManager.RINGER_MODE_SILENT:
                //silent
                playRingtone(context);
                PhoneVibrator(context);
                break;
        }

        Intent myIntent = new Intent(context, MainActivity.class);
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = "GoChat_Message";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            manager.createNotificationChannel(getMessageChannel(channelId));
        }
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(myIntent);
        myIntent.putExtra("notication_type", 1);
        myIntent.putExtra("msg", new Gson().toJson(msg));
        PendingIntent pendingIntent = stackBuilder.getPendingIntent((int) msg.id, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification = new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(msg.notificationTitle())
                .setContentText(msg.notificationContent())
                .setAutoCancel(true)
                .setWhen(java.lang.System.currentTimeMillis())
                .setContentIntent(pendingIntent)
                .build();
        manager.notify((int) msg.id, notification);
    }

    //震动
    public static void PhoneVibrator(Context context) {
        Vibrator myVibrator = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
        myVibrator.cancel();
        myVibrator.vibrate(200);
    }

    private static SoundPool mSound;
    private static int message_sound;
    private static int incoming_sound;

    public static void initRingtone(Context context) {
        if (mSound == null) {
            mSound = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
            message_sound = mSound.load(context, R.raw.message, 1);
            Log.e("playRingtone", "" + message_sound);
            incoming_sound = mSound.load(context, R.raw.ringtone, 1);
            Log.e("initIncomingRing", "" + incoming_sound);
        }
    }

    public static void playRingtone(Context context) {
        if (mSound == null) {
            mSound = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
            message_sound = mSound.load(context, R.raw.message, 1);
            Log.e("playRingtone", "" + message_sound);
        }
        AudioManager mgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        // 获取系统声音的当前音量
        float currentVolume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
        // 获取系统声音的最大音量
        float maxVolume = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        // 获取当前音量的百分比
        float volume = currentVolume / maxVolume;
        // 第一个参数是声效ID,第二个是左声道音量，第三个是右声道音量，第四个是流的优先级，最低为0，第五个是是否循环播放，第六个播放速度(1.0 =正常播放,范围0.5 - 2.0)
        mSound.play(message_sound, volume, volume, 1, 0, 1f);
    }

    private static int incomingStreamID = 0;

    public static void playIncoming(Context context) {
        if (mSound == null) {
            return;
        }
        AudioManager mgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        // 获取系统声音的当前音量
        float currentVolume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
        // 获取系统声音的最大音量
        float maxVolume = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        // 获取当前音量的百分比
        float volume = currentVolume / maxVolume;
        // 第一个参数是声效ID,第二个是左声道音量，第三个是右声道音量，第四个是流的优先级，最低为0，第五个是是否循环播放，第六个播放速度(1.0 =正常播放,范围0.5 - 2.0)
        incomingStreamID = mSound.play(incoming_sound, volume, volume, 1, 0, 1f);
    }

    public static void stopIncoming() {
        if (mSound != null && incomingStreamID != 0) {
            mSound.stop(incomingStreamID);
            incomingStreamID = 0;
        }
    }
}
